const translate = require("google-translate-api");
const fs = require("fs/promises");
const path = require("path");
const cheerio = require("cheerio");

async function main() {
  await handleDir(
    path.resolve(__dirname, "./docs/api/index-files"),
    path.resolve(__dirname, "dist")
  );
  console.log('finish');
  // isDirectory(path.resolve(__dirname, "./docs/legal"));
}

async function trans(content) {
  const { text } = await translate(content, { to: "zh-CN" });
  return text;
}

async function findLastElem(html, select) {
  const elem = select(html);
  const data = elem.children().toArray();
  if (data.length === 0) {
    const text = await trans(elem.text());
    elem.text(text);
    return Promise.resolve(true);
  }
  const arr = data.map(async (v) => {
    const item = select(v);
    return findLastElem(item, select);
  });
  await Promise.allSettled(arr);
  return arr;
}

async function handleHtml(html) {
  const $ = cheerio.load(html);
  await findLastElem("body", $);
  return $("html").html().toString();
}

async function readHtmlContent(link) {
  const fsHtml = await fs.open(link, "r+");
  const html = (await fsHtml.readFile()).toString();
  const trans_data = await handleHtml(html);
  fsHtml.close();
  return trans_data;
}

async function handleDir(src, dist) {
  const srcList = await fs.readdir(src, {
    withFileTypes: true,
  });
  srcList.forEach(async (item) => {
    const srcPath = path.resolve(src, item.name);
    const distPath = path.resolve(dist, item.name);
    if (item.isDirectory()) {
      await fs.mkdir(distPath, {
        recursive: true,
      });
      await handleDir(srcPath, distPath);
    } else {
      const name_list = item.name.split(".");
      const ext = name_list[name_list.length - 1].toLowerCase();
      if (ext === "html") {
        const html_data =await readHtmlContent(srcPath);
        const copy =await fs.open(distPath,'w');
        copy.writeFile(html_data);
        copy.close();
        // console.log(html_data);
      } else {
        await fs.copyFile(srcPath, distPath);
      }
    }
  });
}

main();
